/*
 * @Author: your name
 * @Date: 2022-02-22 22:13:20
 * @LastEditTime: 2024-04-21 22:12:43
 * @LastEditors: cool panda
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /vue3.0-ts-admin/src/utils/request.ts
 */
//1.引入vue
// import Vue from 'vue'
//2.引入axios库
import store from "@/store/index";
import axiosNew from 'axios';
import jsCookie from 'js-cookie'
import router from "../router";

axiosNew.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/api' : "http://abilitychartapi.yanxinfo.com.cn"; // 关键步骤–填写后台请求统一的地址
axiosNew.interceptors.request.use(//请求拦截
    config => {
        // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        const token = jsCookie.get('token')
        if (token) {//如果有token给请求头加上
            config.headers['AccessKey'] = token;
        }
        return config
    },

    err => {
        return Promise.reject(err);
    }

)

axiosNew.interceptors.response.use(response => {//相应拦截
    // try{
    //     let {token}=response.data;
    //     if(token){//将登陆的返回的token保存下来
    //         store.dispatch('tokenChange',token);
    //     }

    // }catch(err){
    //     console.log("在相应拦截这边其他请求不需要取token",err)
    // };

    // if(response.data.code==10001||response.data.code==402){//如果token为空或者过期，跳到登录
    //     store.dispatch('tokenChange',"");
    //     router.push({path:"/login"});
    // }
    return response;
}
    , err => {
        return Promise.reject(err)
    }
);
// axiosNew.defaults.baseURL=""
const axios = function (option: any = {}) {
    return new Promise((resolve, reject) => {
        axiosNew(option).then(res => {
            if (res.data.code === '401') {
                store.commit("SET_TOKEN", null);
                router.push({ path: "/login" });
            }
            resolve(res.data)
        }).catch(err => {
            console.log(err.message);
            if (err.message.includes('401')) {//如果token为空或者过期，跳到登录
                window.localStorage.clear()
                store.commit("SET_TOKEN", null);
                router.push({ path: "/login" });
            }
            resolve(err)
        })
    })
};
export default axios



